package com.learning.platform.service;

import com.learning.platform.dto.CourseResponse;
import com.learning.platform.entity.Course;
import com.learning.platform.entity.UserFavorite;
import com.learning.platform.enums.ErrorCode;
import com.learning.platform.exception.BusinessException;
import com.learning.platform.repository.CourseRepository;
import com.learning.platform.repository.UserFavoriteRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户收藏服务类
 * 处理用户对课程的收藏、取消收藏、查询收藏状态和获取收藏列表等操作
 */
@Service
@Transactional
public class UserFavoriteService {
    
    private final UserFavoriteRepository favoriteRepository;
    private final CourseRepository courseRepository;
    
    /**
     * 构造函数，注入收藏和课程数据访问接口
     * @param favoriteRepository 用户收藏数据访问接口
     * @param courseRepository 课程数据访问接口
     */
    public UserFavoriteService(UserFavoriteRepository favoriteRepository,
                              CourseRepository courseRepository) {
        this.favoriteRepository = favoriteRepository;
        this.courseRepository = courseRepository;
    }
    
    /**
     * 收藏课程
     * @param userId 用户ID
     * @param courseId 课程ID
     * @throws BusinessException 当课程不存在或用户已收藏该课程时抛出
     */
    public void addFavorite(Long userId, Long courseId) {
        // 检查课程是否存在
        courseRepository.findById(courseId)
                .orElseThrow(() -> new BusinessException(ErrorCode.COURSE_NOT_FOUND));
        
        // 检查是否已收藏
        if (favoriteRepository.existsByUserIdAndCourseId(userId, courseId)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "您已经收藏过该课程");
        }
        
        // 创建收藏记录
        UserFavorite favorite = new UserFavorite(userId, courseId);
        favoriteRepository.save(favorite);
    }
    
    /**
     * 取消收藏
     * @param userId 用户ID
     * @param courseId 课程ID
     * @throws BusinessException 当用户未收藏该课程时抛出
     */
    public void removeFavorite(Long userId, Long courseId) {
        UserFavorite favorite = favoriteRepository.findByUserIdAndCourseId(userId, courseId)
                .orElseThrow(() -> new BusinessException(ErrorCode.PARAM_ERROR, "您还未收藏该课程"));
        
        favoriteRepository.delete(favorite);
    }
    
    /**
     * 检查用户是否已收藏课程
     * @param userId 用户ID
     * @param courseId 课程ID
     * @return true表示已收藏，false表示未收藏
     */
    @Transactional(readOnly = true)
    public boolean isFavorited(Long userId, Long courseId) {
        return favoriteRepository.existsByUserIdAndCourseId(userId, courseId);
    }
    
    /**
     * 获取用户的收藏课程列表
     * @param userId 用户ID
     * @param pageable 分页参数
     * @return 用户收藏的课程列表分页数据
     */
    @Transactional(readOnly = true)
    public Page<CourseResponse> getUserFavorites(Long userId, Pageable pageable) {
        Page<UserFavorite> favorites = favoriteRepository.findByUserIdOrderByCreatedAtDesc(userId, pageable);
        
        return favorites.map(favorite -> {
            Course course = courseRepository.findById(favorite.getCourseId()).orElse(null);
            if (course == null) return null;
            
            return new CourseResponse(course);
        });
    }
}
